<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库位名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入库位名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="库位类型" prop="usageType">
        <el-select v-model="queryParams.usageType" placeholder="请选择库位类型" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['stock:location:create']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stock:location:update']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['stock:location:delete']"
        >(关闭/失效)库位</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['stock:location:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <draggable class="wrapper" v-model="stockLocationList">
      <div style="padding: 30px 30px;width:15%" v-for="(item, index) in stockLocationList" :key="index">
        <el-card class="box-card">
          <div slot="header" class="clearfix wrapperTitle">
            <div class="overName"><span><i class="el-icon-receiving" />{{item.name}}</span></div>
            <div><el-tag type="success">{{location_state[item.status]}}</el-tag></div>
            <div><el-checkbox style="padding-left: 15px;" :value="item.checked" @change="stockLocationSelect(index)"></el-checkbox></div>
          </div>
          <div class="stockbnt">

            <div class="pt5 pr5 pb5">
              <el-button type="primary" @click="seeDetail(index)"><i class="el-icon-discount" />查看库位</el-button>
            </div>

            <div class="pt5 pr5 pb5">
              <el-button type="primary"><i class="el-icon-discount" />库存情况</el-button>
            </div>

            <div class="pt5 pr5 pb5">
              <el-button type="primary"><i class="el-icon-set-up" />进行作业</el-button>
            </div>

            <div class="pt5 pr5 pb5">
              <el-button type="primary"><i class="el-icon-guide" />查看调拨</el-button>
            </div>

          </div>
        </el-card>
      </div>
    </draggable>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="800px"
    :before-close="cancel"
    append-to-body>
      <el-button type="primary" v-if="seeLocation" @click="active">激活</el-button>
      <el-button class="pb5 mb20" type="danger" v-if="seeLocation" @click="inactive">失效</el-button>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="seeLocation">
        <el-row>
          <el-col :span="24">
            <div class="card-box">
              <span><i class="el-icon-map-location" /> {{form.completeName}}</span>
            </div>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排序号" prop="sequence">
              <el-input v-model="form.sequence" placeholder="请输入排序号" />
            </el-form-item>   
          </el-col>

          <el-col :span="12">
            <el-form-item label="库位名" prop="name">
              <el-input v-model="form.name" placeholder="请输入库位名" />
            </el-form-item>
          </el-col>          

          <el-col :span="12">
            <el-form-item label="所属仓库" prop="warehouseId">
              <!-- <el-select v-model="form.warehouseId" :disabled="lockWarehouse" placeholder="请选择所属仓库" @change="warehouseChange"> -->
              <el-select v-model="form.warehouseId" placeholder="请选择所属仓库" @change="warehouseChange" value-key="form.warehouseId">
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> 

          <el-col :span="12"  v-if="form.parentId !== 0">
            <el-form-item label="上级库位" prop="parentId">
              <treeselect v-model="form.parentId"
              :disabled="!form.warehouseId"
              :options="stockLocationOptions"
              :normalizer="normalizer" placeholder="选择上级库位"/>
            </el-form-item>
          </el-col>     

          <el-col :span="12">
            <el-form-item label="库位类型" prop="usageType">
              <el-select v-model="form.usageType" placeholder="请选择库位类型">
                <el-option
                  v-for="item in usage_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>              
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="横坐标(x)" prop="posx">
              <el-input v-model="form.posx" placeholder="请输入横坐标(x)" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="货架(y)" prop="posy">
              <el-input v-model="form.posy" placeholder="请输入货架(y)" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="高度(z)" prop="posz">
              <el-input v-model="form.posz" placeholder="请输入高度(z)" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="报废位置?" prop="scrapLocation">
              <el-input v-model="form.scrapLocation" placeholder="请输入是一个报废位置?" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="退回位置?" prop="returnLocation">
              <el-input v-model="form.returnLocation" placeholder="请输入是一个退回位置?" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="下架策略" prop="removalStrategyId">
              <el-input v-model="form.removalStrategyId" placeholder="请输入下架策略" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="存储类型" prop="storageCategoryId">
              <el-input v-model="form.storageCategoryId" placeholder="请输入存储类型" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!seeLocation">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { createLocation, updateLocation, deleteLocation, getLocation, getLocationPage, exportLocationExcel,
listLocationExcludeChild
 } from "@/api/erp/stock/location/location";
import {getSelectWarehouse} from "@/api/erp/stock/warehouse"
import Editor from '@/components/Editor';
import draggable from 'vuedraggable';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Location",
  components: {
    Editor,
    draggable,
    Treeselect
  },
  data() {
    return {
      currentWarehouseId: 0,
      lockWarehouse: false,
      oprateType: 'add',
      usage_type: [],
      location_state: {},
      seeLocation: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 导出遮罩层
      exportLoading: false,
      // 总条数
      total: 0,
      // 仓库库位列表
      stockLocationList: [],
      warehouseList: [],
      // 部门树选项
      stockLocationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        status: null,
        name: null,
        completeName: null,
        usageType: null,
        posx: null,
        posy: null,
        posz: null,
        scrapLocation: null,
        returnLocation: null,
        cyclicInventoryFrequency: null,
        lastInventoryDate: [],
        nextInventoryDate: [],
        parentId: null,
        removalStrategyId: null,
        warehouseId: null,
        storageCategoryId: null,
        description: null,
        sequence: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "库位名不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "所属仓库不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    let rd
    this.getDicts("usage_type").then(response => {
      let dicList = []
      rd = response.data;
      rd.forEach(element => {
        dicList.push({
          'label': element.label,
          'value': element.value,
        })
      });
      this.usage_type = dicList
    });

    this.getDicts("locationState").then(response => {
      let dicData = {}
      rd = response.data;
      rd.forEach(element => {
        dicData[element.value] = element.label
      });
      this.location_state = dicData
      console.log(this.location_state)
    });    

    let warehouseId = this.$route.query.id
    if(warehouseId!=null) {
      this.currentWarehouseId = warehouseId
      getSelectWarehouse(this.currentWarehouseId).then(res => {
        this.warehouseList = res.data
        this.queryParams.warehouseId = parseInt(warehouseId)
        this.form.warehouseId = parseInt(warehouseId)
        this.lockWarehouse = true
        this.getList();       
      })

    }
    else {
      this.getList();
    } 
  },
  Mounted() {
    
  },
  methods: {
    active() {
      const h = this.$createElement;

      this.$notify({
        title: '提示',
        message: h('i', { style: 'color: teal'}, '这个激活功能后面再做')
      });      
    },
    inactive() {
      const h = this.$createElement;

      this.$notify({
        title: '提示',
        message: h('i', { style: 'color: teal'}, '这个失效功能后面再做')
      });      
    },    
    warehouseChange(makeType) {
      let id = this.oprateType == 'add'?0:this.currentSelectStockLocation.id
      listLocationExcludeChild(id, this.form.warehouseId).then(response => {
        response.data.forEach(item => {
          item.parentId = parseInt(item.parentId)
        })
        this.stockLocationOptions = this.handleTree(response.data, "id");
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查看库位详情 */
    seeDetail(index) {
      this.currentSelectStockLocation= this.stockLocationList[index]
      this.seeLocation = true
      this.handleUpdate(this.currentSelectStockLocation)
    },
    /** 勾选仓库 */
    stockLocationSelect(index) {
      this.stockLocationList[index].checked = !this.stockLocationList[index].checked
      let checkedNum = 0
      this.locationIds = []
      this.stockLocationList.forEach(item => {
        if(item.checked) {
          checkedNum++
          this.locationIds.push({id: item.id, name: item.name})
        }
      })
      if(checkedNum > 0) {
        this.single = false
        this.multiple = false
        this.currentSelectStockLocation= this.stockLocationList[index]
      }
      if(checkedNum === 0) {
        this.single = true
        this.multiple = true
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getLocationPage(this.queryParams).then(response => {
        this.stockLocationList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.seeLocation = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        status: undefined,
        name: undefined,
        completeName: undefined,
        usageType: undefined,
        posx: undefined,
        posy: undefined,
        posz: undefined,
        scrapLocation: undefined,
        returnLocation: undefined,
        cyclicInventoryFrequency: undefined,
        lastInventoryDate: undefined,
        nextInventoryDate: undefined,
        parentId: undefined,
        removalStrategyId: undefined,
        warehouseId: undefined,
        storageCategoryId: undefined,
        description: undefined,
        sequence: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.oprateType = 'add';
      this.open = true;
      this.title = "添加仓库库位";
      getSelectWarehouse(this.currentWarehouseId).then(res => {
        this.warehouseList = res.data
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row?row.id:this.currentSelectStockLocation.id;
      this.oprateType = 'update';
      getLocation(id).then(response => {
        this.form = response.data;
        if(this.seeLocation) {
          // 为了解决e-select e-option在查看时候会显示id的情况
          this.form.warehouseId = parseInt(this.form.warehouseId)
        }
        this.open = true;
        this.title = this.seeLocation?"查看库位":"修改仓库库位";

        getSelectWarehouse(this.currentWarehouseId).then(res => {
          this.warehouseList = res.data
        })      
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateLocation(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createLocation(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认失效仓库库位编号为"' + id + '"的数据项?').then(function() {
          return deleteLocation(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有仓库库位数据项?').then(() => {
          this.exportLoading = true;
          return exportLocationExcel(params);
        }).then(response => {
          this.$download.excel(response, '仓库库位.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.wrapper {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-flow:row wrap;
}
.wrapperTitle {
  display: flex;
  justify-content: flex-start;
  width: 100%;
}
.item{
  color: #26e22f;
  padding: 25px 25px;
}
.stockbnt {
  display: flex;
  flex-flow:row wrap;
  width: 100%;
}
.overName {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 200px;
  font-size: 15px;
}
</style>
